﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Data;
using System.Data.Objects;
using System.Data.Entity.Infrastructure;

namespace Organizer.Server
{
    class ServiceContext : DbContext
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public ServiceContext()
        {
            log.Trace(System.Reflection.MethodBase.GetCurrentMethod().Name + " called");

            Configuration.AutoDetectChangesEnabled = true;
            Configuration.LazyLoadingEnabled = true;
            Configuration.ProxyCreationEnabled = true;
            Configuration.ValidateOnSaveEnabled = true;
        }


        public DbSet<Model.Movie.Wish> Movies_Wish { get; set; }

        #region overrides
        public ObjectContext ObjectContext()
        {
            log.Trace(System.Reflection.MethodBase.GetCurrentMethod().Name + " called");

            return (this as IObjectContextAdapter).ObjectContext;
        }

        public override int SaveChanges()
        {
            log.Trace(System.Reflection.MethodBase.GetCurrentMethod().Name + " called");

            foreach (ObjectStateEntry entry in ObjectContext().ObjectStateManager.GetObjectStateEntries(EntityState.Added))
            {
                if (entry.IsRelationship && entry.Entity.GetType() == typeof(Model.Item))
                {
                    Model.Item item = entry.Entity as Model.Item;

                    item.Inserted = DateTime.UtcNow;
                    item.Updated = DateTime.UtcNow;
                }
            }

            foreach (ObjectStateEntry entry in ObjectContext().ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
            {
                if (entry.IsRelationship && entry.Entity.GetType() == typeof(Model.Item))
                {
                    Model.Item item = entry.Entity as Model.Item;

                    item.Updated = DateTime.UtcNow;
                }
            }

            return base.SaveChanges();
        }

        protected override void Dispose(bool disposing)
        {
            log.Trace(System.Reflection.MethodBase.GetCurrentMethod().Name + " called");

            Configuration.LazyLoadingEnabled = false;
            base.Dispose(disposing);
        }
        #endregion overrides
    }
}
